import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/empty_widget.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/common/toast_util.dart';
import 'package:gzmall_app/goods/goods_details_page.dart';
import 'package:gzmall_app/model/order_item.dart';
import 'package:gzmall_app/model/shopping_cart.dart';
import 'package:gzmall_app/shoppping_cart/confirm_order.dart';
import 'package:gzmall_app/store/store_detail_page.dart';
import "package:pull_to_refresh/pull_to_refresh.dart";
import 'dart:async';
import 'package:gzmall_app/common/color_common.dart';
import 'package:flutter/cupertino.dart';
import 'package:dio/dio.dart';
import 'package:common_utils/common_utils.dart';

class ShoppingCartWidget extends StatefulWidget {
  Function onSelectTab;

  ShoppingCartWidgetState shoppingCartWidgetState;

  ShoppingCartWidget({this.onSelectTab});

  @override
  State<StatefulWidget> createState() {
    shoppingCartWidgetState =
        ShoppingCartWidgetState(onSelectTab: this.onSelectTab);
    return shoppingCartWidgetState;
  }

  initData() {
    shoppingCartWidgetState._onRefresh(true);
  }
}

class ShoppingCartWidgetState extends State<ShoppingCartWidget> {
  Function onSelectTab;

  double _topPadding;
  double _bottomPadding;

  RefreshListView _refreshListView;

  int _currentParentIndex, _currentChildIndex;
  List<ShoppingCart> _shoppingCartList = [];
  bool isSelectAll = false;
  double _totalPrice = 0.0;
  int _totalCount = 0;

  ShoppingCartWidgetState({this.onSelectTab});

  @override
  void initState() {
    super.initState();
    _getShoppingCart(false);
  }

  @override
  Widget build(BuildContext context) {
    init();
    return Container(
      decoration: BoxDecoration(color: ColorCommon.grey5),
      child: Column(
        children: <Widget>[
          _createTitleBar(),
          Expanded(
              child: _shoppingCartList != null && _shoppingCartList.length > 0
                  ? _createRefresh(context)
                  : EmptyWidget(reloadAction: () {
                      _onRefresh(true);
                    })),
          _createBottomBar(),
        ],
      ),
    );
  }

  void init() {
    _topPadding = MediaQuery.of(context).padding.top;
    _bottomPadding = MediaQuery.of(context).padding.bottom;
  }

  _createRefresh(BuildContext context) {
    _refreshListView = RefreshListView(
      onRefresh: _onRefresh,
      child: ListView.builder(
        padding: EdgeInsets.only(top: 0.0),
        itemCount: _shoppingCartList.length,
        itemBuilder: (context, index) {
          return _createShoppingCartItem(index, _shoppingCartList[index]);
        },
      ),
    );
    return _refreshListView;
  }

  _createTitleBar() {
    return Container(
      padding: EdgeInsets.fromLTRB(10.0, _topPadding + 10.0, 10.0, 10.0),
      color: ColorCommon.primaryColor,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text(
            "购物车",
            style: TextStyle(color: Colors.white, fontSize: 18.0),
          ),
        ],
      ),
    );
  }

  _onRefresh(bool up) {
    if (up) {
      _getShoppingCart(true);
    }
  }

  _onOffsetChange(bool up, double offset) {}

  _createShoppingCartItem(int parentIndex, ShoppingCart sc) {
    List<Widget> _items = [];
    if (sc != null && sc.orderItems != null && sc.orderItems.length > 0) {
      int index = 0;
      _items = sc.orderItems.map((i) {
        Widget _itemWidget =
            _createShoppingCartGoodsItem(parentIndex, index, i);
        index++;
        return _itemWidget;
      }).toList();
    } else {
      _items.add(Container());
    }
    return Container(
      margin: const EdgeInsets.only(bottom: 10.0),
      child: Column(
        children: <Widget>[
          Container(
            color: Colors.white,
            margin: const EdgeInsets.only(bottom: 1.0),
            padding: const EdgeInsets.only(
                left: 5.0, right: 15.0, top: 5.0, bottom: 5.0),
            child: Row(children: <Widget>[
              Checkbox(
                value: sc.isSelected,
                onChanged: (isCheck) {
                  _selectShoppingCartparent(parentIndex, isCheck);
                },
              ),
              InkWell(
                onTap: () {},
                child: Text(
                  sc != null ? sc.shopName : "",
                  style: TextStyle(
                      fontSize: 16.0,
                      fontWeight: FontWeight.bold,
                      color: ColorCommon.black1),
                ),
              ),
            ]),
          ),
          Column(
            children: _items,
          ),
        ],
      ),
    );
  }

  _createShoppingCartGoodsItem(
      int parentIndex, int childIndex, OrderItem item) {
    Function onTap = () {
      Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
        return new GoodsDetailsPage(productId: item.spuId);
      })).then((v) {
        _getShoppingCart(true);
        if (!mounted) return;
        setState(() {
          _currentParentIndex = 0;
          _currentChildIndex = 0;
          isSelectAll = false;
          _totalPrice = 0.0;
          _totalCount = 0;
        });
      });
    };
    return Slidable(
      delegate: SlidableDrawerDelegate(),
      actionExtentRatio: 0.25,
      child: Container(
        color: Colors.white,
        margin: const EdgeInsets.only(bottom: 1.0),
        padding: const EdgeInsets.only(
            left: 5.0, right: 15.0, top: 10.0, bottom: 10.0),
        child: Row(children: <Widget>[
          Checkbox(
            value: item.isSelected,
            onChanged: (isCheck) {
              _selectShoppingCartItem(parentIndex, childIndex, isCheck);
            },
          ),
          Expanded(
            child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  InkWell(
                    onTap: onTap,
                    child: item.avatar != null
                        ? CachedNetworkImage(
                            imageUrl: item.avatar,
                            fit: BoxFit.fill,
                            width: 80.0,
                            height: 80.0,
                          )
                        : Container(
                            width: 80.0,
                            height: 80.0,
                            color: Colors.grey,
                          ),
                  ),
                  Expanded(
                    child: Container(
                      margin: const EdgeInsets.only(left: 20.0),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          InkWell(
                            onTap: onTap,
                            child: Container(
                                child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  item != null ? item.name : "",
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                      fontSize: 16.0,
                                      color: ColorCommon.black1),
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(top: 2.0),
                                  child: Text(
                                    item != null
                                        ? item.optionValuePresentation
                                        : "",
                                    style: TextStyle(
                                        fontSize: 14.0,
                                        color: ColorCommon.grey3),
                                  ),
                                ),
                              ],
                            )),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(top: 8.0),
                            child: Row(
                              children: <Widget>[
                                Expanded(
                                  child: Text(
                                    "¥" +
                                        (item != null
                                            ? item.fee.toString()
                                            : "0.0"),
                                    style: TextStyle(
                                        fontSize: 18.0,
                                        color: ColorCommon.primaryColor),
                                  ),
                                ),
                                Row(
                                  children: <Widget>[
                                    GestureDetector(
                                      onTap: () {
                                        if (item.quantity > 1) {
                                          _currentParentIndex = parentIndex;
                                          _currentChildIndex = childIndex;
                                          _updateShoppingCart(
                                              item.id, item.quantity - 1);
                                        }
                                      },
                                      child: Container(
                                        width: 37.0,
                                        height: 30.0,
                                        alignment: Alignment.center,
                                        decoration: BoxDecoration(
                                          color: ColorCommon.grey2,
                                        ),
                                        child: Text(
                                          "-",
                                          style: TextStyle(fontSize: 16.0),
                                        ),
                                      ),
                                    ),
                                    Container(
                                      width: 45.0,
                                      height: 30.0,
                                      alignment: Alignment.center,
                                      decoration: BoxDecoration(
                                        color: ColorCommon.grey2,
                                      ),
                                      child: Text(item != null
                                          ? item.quantity.toString()
                                          : "1"),
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        _currentParentIndex = parentIndex;
                                        _currentChildIndex = childIndex;
                                        _updateShoppingCart(
                                            item.id, item.quantity + 1);
                                      },
                                      child: Container(
                                        width: 37.0,
                                        height: 30.0,
                                        alignment: Alignment.center,
                                        decoration: BoxDecoration(
                                          color: ColorCommon.grey2,
                                        ),
                                        child: Text(
                                          "+",
                                          style: TextStyle(fontSize: 16.0),
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ]),
          ),
        ]),
      ),
      secondaryActions: <Widget>[
        IconSlideAction(
          caption: '删除',
          color: Colors.red,
          icon: Icons.delete,
          onTap: () {
            _currentParentIndex = parentIndex;
            _currentChildIndex = childIndex;
            _deleteShoppingCart(item.id);
          },
        ),
      ],
    );
  }

  _createBottomBar() {
    return Container(
      color: Colors.white,
      margin: const EdgeInsets.only(top: 1.0),
      child: Row(mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[
        Checkbox(
          value: isSelectAll,
          onChanged: (isCheck) {
            _selectAll(isCheck);
          },
        ),
        Expanded(
          child: Text(
            "全选",
            style: TextStyle(fontSize: 14.0, color: ColorCommon.black1),
            maxLines: 1,
          ),
        ),
        Text(
          "合计金额:",
          style: TextStyle(fontSize: 14.0, color: ColorCommon.black1),
          maxLines: 1,
        ),
        Padding(
          padding: const EdgeInsets.only(left: 10.0, right: 10.0),
          child: Text(
            "¥" + _totalPrice.toString(),
            style: TextStyle(fontSize: 16.0, color: ColorCommon.primaryColor),
            maxLines: 1,
          ),
        ),
        InkWell(
          onTap: () {
            List<ShoppingCart> _selectShoppingCart = [];
            for (var cart in _shoppingCartList) {
              List<OrderItem> _selectOrderItems = [];
              if (cart.orderItems != null && cart.orderItems.length > 0) {
                for (var item in cart.orderItems) {
                  if (item.isSelected) {
                    _selectOrderItems.add(item);
                  }
                }
              }
              if (_selectOrderItems.length > 0) {
                ShoppingCart sc =
                    ShoppingCart(cart.shopName, _selectOrderItems);
                _selectShoppingCart.add(sc);
              }
            }
            if (_selectShoppingCart.length > 0) {
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return ConfirmOrderPage(
                  shoppingCartList: _selectShoppingCart,
                );
              })).then((v) {
                _getShoppingCart(true);
                if (!mounted) return;
                setState(() {
                  _currentParentIndex = 0;
                  _currentChildIndex = 0;
                  isSelectAll = false;
                  _totalPrice = 0.0;
                  _totalCount = 0;
                });
              });
            } else {
              ToastUtil.showMessageToast("请选择购物车");
            }
          },
          child: Container(
            color: ColorCommon.primaryColor,
            height: 50.0,
            alignment: Alignment.center,
            padding: const EdgeInsets.only(left: 25.0, right: 25.0),
            child: Text(
              "结算(" + _totalCount.toString() + ")",
              style: TextStyle(fontSize: 16.0, color: Colors.white),
            ),
          ),
        ),
      ]),
    );
  }

  _selectAll(bool isSelect) {
    isSelectAll = isSelect;
    if (_shoppingCartList.length > 0) {
      for (var i = 0; i < _shoppingCartList.length; i++) {
        _selectShoppingCartparent(i, isSelect);
      }
    }
  }

  _selectShoppingCartparent(int parentIndex, bool isSelect) {
    if (_shoppingCartList.length > parentIndex) {
      if (_shoppingCartList[parentIndex] != null) {
        if (!mounted) return;
        setState(() {
          _shoppingCartList[parentIndex].isSelected = isSelect;
          if (_shoppingCartList[parentIndex].orderItems.length > 0) {
            for (var i = 0;
                i < _shoppingCartList[parentIndex].orderItems.length;
                i++) {
              _selectShoppingCartItem(parentIndex, i, isSelect);
            }
          }
          isSelectAll = _isSelectParentAll();
          _settle();
        });
      }
    }
  }

  _selectShoppingCartItem(int parentIndex, int childIndex, bool isSelect) {
    if (_shoppingCartList.length > parentIndex) {
      if (_shoppingCartList[parentIndex] != null &&
          _shoppingCartList[parentIndex].orderItems.length > childIndex) {
        if (!mounted) return;
        setState(() {
          _shoppingCartList[parentIndex].orderItems[childIndex].isSelected =
              isSelect;
          _shoppingCartList[parentIndex].isSelected =
              _isSelectParentOrderItem(_shoppingCartList[parentIndex].shopName);
          isSelectAll = _isSelectParentAll();
          _settle();
        });
      }
    }
  }

  bool _isSelectParentAll() {
    if (_shoppingCartList.length > 0) {
      for (var item in _shoppingCartList) {
        if (!item.isSelected) {
          return false;
        }
      }
      return true;
    }
    return false;
  }

  bool _isSelectOrderItem(int id) {
    if (_shoppingCartList != null && _shoppingCartList.length > 0) {
      for (var item in _shoppingCartList) {
        if (item.orderItems != null && item.orderItems.length > 0) {}
        for (var item2 in item.orderItems) {
          if (item2.id == id) {
            return item2.isSelected;
          }
        }
      }
    }
    return false;
  }

  bool _isSelectParentOrderItem(String shopName) {
    if (_shoppingCartList != null && _shoppingCartList.length > 0) {
      for (var item in _shoppingCartList) {
        if (item.shopName == shopName &&
            item.orderItems != null &&
            item.orderItems.length > 0) {
          for (var item in item.orderItems) {
            if (!item.isSelected) {
              return false;
            }
          }
          return true;
        }
      }
    }
    return false;
  }

  _settle() {
    _totalPrice = 0.0;
    _totalCount = 0;
    for (var pItem in _shoppingCartList) {
      if (pItem.orderItems != null && pItem.orderItems.length > 0) {
        for (var item in pItem.orderItems) {
          if (item.isSelected) {
            _totalPrice +=
                NumUtil.multiply(double.parse(item.fee), item.quantity);
            _totalCount += item.quantity;
          }
        }
      }
    }
  }

  _checkSelectParentOrderItem() {
    if (_shoppingCartList != null && _shoppingCartList.length > 0) {
      for (var item in _shoppingCartList) {
        if (item.orderItems != null && item.orderItems.length > 0) {
          bool isSelect = true;
          for (var item in item.orderItems) {
            if (!item.isSelected) {
              isSelect = false;
            }
          }
          item.isSelected = isSelect;
        }
      }
    }
  }

  _checkSettle() {
    if (!mounted) return;
    setState(() {
      _checkSelectParentOrderItem();
      isSelectAll = _isSelectParentAll();
      _settle();
    });
  }

  Widget _getTagView(
      String text, Color bgColor, Color borderColor, Color textColor,
      {DecorationImage image}) {
    BoxDecoration decoration;
    if (image == null) {
      decoration = BoxDecoration(
          color: bgColor,
          border: Border.all(color: borderColor),
          borderRadius: BorderRadius.all(Radius.circular(100.0)));
    } else {
      decoration = BoxDecoration(image: image);
    }
    return Container(
      padding: const EdgeInsets.only(left: 8.0, right: 8.0),
      decoration: decoration,
      child: Text(
        text,
        style: TextStyle(fontSize: 16.0, color: textColor),
      ),
    );
  }

  _getShoppingCart(bool isInterceptError) {
    NetUtil.get(
        context,
        Api.orderItems,
        (data, message) {
          if (!mounted) return;
          if (isInterceptError && _refreshListView != null) {
            _refreshListView.refreshCompleted(true);
          }
          setState(() {
            List<ShoppingCart> cartList = (data as List)
                ?.map((e) => e == null ? null : ShoppingCart.fromJson(e))
                ?.toList();
            _shoppingCartList = cartList.map((i) {
              i.orderItems = i.orderItems.map((i2) {
                i2.isSelected = _isSelectOrderItem(i2.id);
                return i2;
              }).toList();
              i.isSelected = _isSelectParentOrderItem(i.shopName);
              return i;
            }).toList();
            _checkSettle();
          });
        },
        isInterceptError: isInterceptError,
        errorCallBack: (e) {
          if (!mounted) return;
          if (isInterceptError && _refreshListView != null) {
            _refreshListView.refreshCompleted(true);
          }
        });
  }

  _deleteShoppingCart(int id) {
    NetUtil.delete(context, Api.orderItems + "/" + id.toString(),
        (data, message) {
      ToastUtil.showMessageToast(message);

      if (!mounted) return;
      setState(() {
        if (_shoppingCartList.length > _currentParentIndex) {
          if (_shoppingCartList[_currentParentIndex].orderItems != null &&
              _shoppingCartList[_currentParentIndex].orderItems.length >
                  _currentChildIndex) {
            _shoppingCartList[_currentParentIndex]
                .orderItems
                .removeAt(_currentChildIndex);
            if (_shoppingCartList[_currentParentIndex].orderItems.length <= 0) {
              _shoppingCartList.removeAt(_currentParentIndex);
            }
          }
        }
        _checkSettle();
      });
    });
  }

  _updateShoppingCart(int id, int quantity) {
    FormData formData = new FormData.fromMap({
      "quantity": quantity,
    });

    NetUtil.put(
      context,
      Api.orderItems + "/" + id.toString(),
      (data, message) {
        ToastUtil.showMessageToast(message);

        if (!mounted) return;
        setState(() {
          if (_shoppingCartList.length > _currentParentIndex) {
            if (_shoppingCartList[_currentParentIndex].orderItems != null &&
                _shoppingCartList[_currentParentIndex].orderItems.length >
                    _currentChildIndex) {
              _shoppingCartList[_currentParentIndex]
                  .orderItems[_currentChildIndex]
                  .quantity = quantity;
            }
          }
          _checkSettle();
        });
      },
      params: formData,
    );
  }
}
